package com.emex.app.stuff.company;

import com.emex.app.shared.data.CompanyInfo;
import com.emex.app.shared.data.JuridicalPerson;
import com.emex.app.stuff.juridic.SearchJuridicPersonDialog;
import com.emex.app.stuff.provider.CompanyInfoDataProvider;
import com.emex.app.stuff.provider.JuridicalPersonDataProvider;
import com.emex.app.stuff.utils.UIUtils;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.List;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import org.openide.windows.WindowManager;

/**
 *
 * @author Sergey
 */
public class CompanyInfoDialog extends javax.swing.JDialog {

    private CompanyInfo companyInfo;

    private JuridicalPerson client;

    /**
     * Creates new form CompanyInfoDialog
     */
    public CompanyInfoDialog(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        customInit();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        loadImageButton = new javax.swing.JButton();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jurPersonField = new javax.swing.JTextField();
        loadIPButton = new javax.swing.JButton();
        addressField = new javax.swing.JTextField();
        phonesField = new javax.swing.JTextField();
        jScrollPane1 = new javax.swing.JScrollPane();
        scheduleArea = new javax.swing.JTextArea();
        saveButton = new javax.swing.JButton();
        cancelButton = new javax.swing.JButton();
        imageViewer = new org.jdesktop.swingx.JXImageView();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle(org.openide.util.NbBundle.getMessage(CompanyInfoDialog.class, "CompanyInfoDialog.title")); // NOI18N

        org.openide.awt.Mnemonics.setLocalizedText(jLabel1, org.openide.util.NbBundle.getMessage(CompanyInfoDialog.class, "CompanyInfoDialog.jLabel1.text")); // NOI18N

        org.openide.awt.Mnemonics.setLocalizedText(loadImageButton, org.openide.util.NbBundle.getMessage(CompanyInfoDialog.class, "CompanyInfoDialog.loadImageButton.text")); // NOI18N
        loadImageButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                loadImageButtonActionPerformed(evt);
            }
        });

        org.openide.awt.Mnemonics.setLocalizedText(jLabel2, org.openide.util.NbBundle.getMessage(CompanyInfoDialog.class, "CompanyInfoDialog.jLabel2.text")); // NOI18N

        org.openide.awt.Mnemonics.setLocalizedText(jLabel3, org.openide.util.NbBundle.getMessage(CompanyInfoDialog.class, "CompanyInfoDialog.jLabel3.text")); // NOI18N

        org.openide.awt.Mnemonics.setLocalizedText(jLabel4, org.openide.util.NbBundle.getMessage(CompanyInfoDialog.class, "CompanyInfoDialog.jLabel4.text")); // NOI18N

        org.openide.awt.Mnemonics.setLocalizedText(jLabel5, org.openide.util.NbBundle.getMessage(CompanyInfoDialog.class, "CompanyInfoDialog.jLabel5.text")); // NOI18N

        jurPersonField.setText(org.openide.util.NbBundle.getMessage(CompanyInfoDialog.class, "CompanyInfoDialog.jurPersonField.text")); // NOI18N

        loadIPButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/view.png"))); // NOI18N
        org.openide.awt.Mnemonics.setLocalizedText(loadIPButton, org.openide.util.NbBundle.getMessage(CompanyInfoDialog.class, "CompanyInfoDialog.loadIPButton.text")); // NOI18N
        loadIPButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                loadIPButtonActionPerformed(evt);
            }
        });

        addressField.setText(org.openide.util.NbBundle.getMessage(CompanyInfoDialog.class, "CompanyInfoDialog.addressField.text")); // NOI18N

        phonesField.setText(org.openide.util.NbBundle.getMessage(CompanyInfoDialog.class, "CompanyInfoDialog.phonesField.text")); // NOI18N

        scheduleArea.setColumns(20);
        scheduleArea.setRows(5);
        jScrollPane1.setViewportView(scheduleArea);

        saveButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/save.png"))); // NOI18N
        org.openide.awt.Mnemonics.setLocalizedText(saveButton, org.openide.util.NbBundle.getMessage(CompanyInfoDialog.class, "CompanyInfoDialog.saveButton.text")); // NOI18N
        saveButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                saveButtonActionPerformed(evt);
            }
        });

        cancelButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/cancel.png"))); // NOI18N
        org.openide.awt.Mnemonics.setLocalizedText(cancelButton, org.openide.util.NbBundle.getMessage(CompanyInfoDialog.class, "CompanyInfoDialog.cancelButton.text")); // NOI18N
        cancelButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cancelButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout imageViewerLayout = new javax.swing.GroupLayout(imageViewer);
        imageViewer.setLayout(imageViewerLayout);
        imageViewerLayout.setHorizontalGroup(
            imageViewerLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 602, Short.MAX_VALUE)
        );
        imageViewerLayout.setVerticalGroup(
            imageViewerLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 59, Short.MAX_VALUE)
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(imageViewer, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(loadImageButton))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addComponent(jLabel4, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jLabel2, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jLabel3, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jLabel5, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 155, Short.MAX_VALUE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jurPersonField, javax.swing.GroupLayout.PREFERRED_SIZE, 391, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(loadIPButton, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE))
                            .addComponent(addressField)
                            .addComponent(phonesField)
                            .addComponent(jScrollPane1)))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(saveButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(cancelButton)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(loadImageButton))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(imageViewer, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(loadIPButton, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jurPersonField, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(addressField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(phonesField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel5)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 58, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(saveButton)
                    .addComponent(cancelButton))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void loadImageButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_loadImageButtonActionPerformed
        JFileChooser fc = new JFileChooser();
        int res = fc.showOpenDialog(null);
        // We have an image!
        try {
            if (res == JFileChooser.APPROVE_OPTION) {
                File file = fc.getSelectedFile();
                setImageIcon(file);
                companyInfo.setLogo(Files.readAllBytes(file.toPath()));
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }

    }//GEN-LAST:event_loadImageButtonActionPerformed

    private void loadIPButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_loadIPButtonActionPerformed
        if (null != jurPersonField.getText()
                && !jurPersonField.getText().isEmpty()) {
            List<JuridicalPerson> foundClient = JuridicalPersonDataProvider.getInstance().
                    getAllJuridicalPeronsByName(jurPersonField.getText());

            if (foundClient.isEmpty()) {
                UIUtils.showInfoMessage("Клиентов с заданными данными нет в базе");
            } else if (foundClient.size() == 1) {
                this.client = foundClient.get(0);
            } else {
                // Clients more than 1 - show table to choose correct one
                SearchJuridicPersonDialog dialog = new SearchJuridicPersonDialog(WindowManager.getDefault().getMainWindow(), true, foundClient);
                dialog.setLocationRelativeTo(null);
                dialog.setVisible(true);
                client = dialog.getClient();
            }

            if (null != client) {
                jurPersonField.setText(client.getName());
            }
        }
    }//GEN-LAST:event_loadIPButtonActionPerformed

    private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed
        setVisible(false);
    }//GEN-LAST:event_cancelButtonActionPerformed

    private void saveButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveButtonActionPerformed
        if (companyInfo.getLogo() == null
                || jurPersonField.getText().isEmpty()
                || addressField.getText().isEmpty()
                || phonesField.getText().isEmpty()
                || scheduleArea.getText().isEmpty()) {
            UIUtils.showErrorMessage("Все поля обязательны для заполнения");
            return;
        }
        boolean isCreate = false;
        if (companyInfo.getAddress() == null) {
            isCreate = true;
        }
        companyInfo.setAddress(addressField.getText());
        companyInfo.setPhones(phonesField.getText());
        companyInfo.setSchedule(scheduleArea.getText());
        companyInfo.setJurPersonId(client.getId());
        if (isCreate) {
            CompanyInfoDataProvider.getInstance().insertCompanyInfo(companyInfo);
        } else {
            CompanyInfoDataProvider.getInstance().updateCompanyInfo(companyInfo);
        }
        setVisible(false);
    }//GEN-LAST:event_saveButtonActionPerformed

    private void setImageIcon(File file) throws IOException {
        imageViewer.setImage(file);
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTextField addressField;
    private javax.swing.JButton cancelButton;
    private org.jdesktop.swingx.JXImageView imageViewer;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextField jurPersonField;
    private javax.swing.JButton loadIPButton;
    private javax.swing.JButton loadImageButton;
    private javax.swing.JTextField phonesField;
    private javax.swing.JButton saveButton;
    private javax.swing.JTextArea scheduleArea;
    // End of variables declaration//GEN-END:variables

    private void customInit() {
        companyInfo = CompanyInfoDataProvider.getInstance().getCompanyInfo();
        if (null != companyInfo) {
            ImageIcon icon = new ImageIcon(companyInfo.getLogo());
            imageViewer.setImage(icon.getImage());
            client = JuridicalPersonDataProvider.getInstance().selectJuridicalPersonByPrimaryKey(companyInfo.getJurPersonId());
            jurPersonField.setText(client.getName());
            addressField.setText(companyInfo.getAddress());
            phonesField.setText(companyInfo.getPhones());
            scheduleArea.setText(companyInfo.getSchedule());
        } else {
            companyInfo = new CompanyInfo();
        }
    }
}
